package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Friendship;
import cn.wolfcode.trip.base.domain.FriendshipPraise;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.AttentionMapper;
import cn.wolfcode.trip.base.mapper.FriendshipMapper;
import cn.wolfcode.trip.base.mapper.FriendshipPraiseMapper;
import cn.wolfcode.trip.base.query.FriendshipQueryObject;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IFriendshipService;
import cn.wolfcode.trip.base.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FriendshipServiceImpl implements IFriendshipService {

    @Autowired
    private FriendshipMapper friendshipMapper;

    @Autowired
    private AttentionMapper attentionMapper;

    @Autowired
    private FriendshipPraiseMapper praiseMapper;

    @Override
    public PageInfo<Friendship> getFirendshipById(Long friendshipId) {
        List<Friendship> list= friendshipMapper.selectByfriendshipId(friendshipId);
        return new PageInfo<>(list);
    }


    @Override
    public PageInfo<Friendship> query(FriendshipQueryObject qo) {
        User user = UserContext.getCurrentUser();
        //通过被关注者查出所有的关注者
        Long id = UserContext.getCurrentUser().getId();
        List<Long> userIds=attentionMapper.selectAttentionUserByBeAttentionUser(id);
        userIds.add(id);

        //朋友圈只能看到自己和自己关注的用户的朋友圈
        qo.setUserIds(userIds);
        PageHelper.startPage(qo.getCurrentPage(),0);
        List<Friendship> list= friendshipMapper.selectByUserIds(qo);
        //遍历每条朋友圈
        for (Friendship f:list) {
            List<User> users = f.getFriendshipPraises();
            //遍历每条朋友圈的点赞的user
            for (User u1 : users) {
                //如果点赞user的id跟现在登录用户的id相同
                if (u1.getId().equals(user.getId())) {
                    //那么就给该条朋友圈的isGood设置true
                    f.setIsGood(true);
                }
            }
        }


        return new PageInfo<>(list);
    }

    @Override
    public void saveFriendship(Friendship friendship) {
        friendship.setUser(UserContext.getCurrentUser());

        friendshipMapper.insert(friendship);
    }

    //保存点赞
    @Override
    public void saveGood(FriendshipPraise praise) {
        praise.setPraiseuser(UserContext.getCurrentUser());
        praiseMapper.insert(praise);
    }

    //删除点赞
    @Override
    public void deleteGood(Long friendshipId) {
        Long uId = UserContext.getCurrentUser().getId();
        praiseMapper.deleteByFidAndUserId(friendshipId,uId);
    }

    @Override
    public Object getGood(Long friendshipId) {
        Long uId = UserContext.getCurrentUser().getId();

        return praiseMapper.selectByFidAndUid(friendshipId,uId);
    }


}
